using AutoMapper;
using Core.SimpleTemp.Application;
using Core.SimpleTemp.Application.common;
using Core.SimpleTemp.Application.UserApp;
using Core.SimpleTemp.Common.Authorization;
using Core.SimpleTemp.Common.PagingQuery;
using Core.SimpleTemp.Entitys;
using Core.SimpleTemp.Mvc.Api.Internal;
using Core.SimpleTemp.Repositories.Internal;
using Core.Toolkit.Authorization;
using Core.Toolkit.Core;
using Core.Toolkit.Core.Api;
using Core.Toolkit.Core.Repositories;
using Core.Toolkit.Message;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Threading.Tasks;

namespace Core.SimpleTemp.Mvc.Api.sys
{
    /// <summary>
    /// FL_BasisInformation
    ///</summary>
    [ApiExplorerSettings(GroupName = "Sys")]//swagger分类标签
    [Route("api/[controller]")]//路由说明
    [EnableCors("any")]//跨域规则
    [ApiController]//APi标识Controller
    public class FL_BasisInformationController : CoreApiController
    {
        private readonly CoreDBContext _coreDBContext;
        private readonly FL_BasisInformationService _service;
        private readonly FL_BasisInformationCheckService _serviceCheck;
        private readonly FL_StandardInformationService _Informationservice;
        private readonly SysUserAppService _Userservice;
        private readonly WrkerRelationsService _wrkerRelationsService;
        private readonly BusinessOptions _businessOptions;
        SQLHelper _sQLHelper;
        CoreDBContext _dbContext;
        private readonly IMessage _message;
        /// <summary>
        /// FL_BasisInformation
        ///</summary>
        public FL_BasisInformationController(FL_BasisInformationService service, CoreDBContext coreDBContext,  SysUserAppService Userservice, IMessage message, WrkerRelationsService wrkerRelationsService, IOptionsMonitor<BusinessOptions> businessOptions, FL_BasisInformationCheckService serviceCheck, CoreDBContext dbContext, FL_StandardInformationService Informationservice, SQLHelper sQLHelper)
        {
            _Informationservice = Informationservice;
            _service = service;
            _serviceCheck = serviceCheck;
            _coreDBContext = coreDBContext;
            _Userservice = Userservice;
            _dbContext = dbContext;
            _message = message;
            _wrkerRelationsService = wrkerRelationsService;
            _businessOptions = businessOptions.CurrentValue;
            _sQLHelper = sQLHelper;
        }

        #region 基础增删改查
        /// <summary>
        /// 查询
        ///</summary>
        /// <param name="pagingQueryModel"></param>
        /// <returns></returns>

        [HttpPost("GetList")]
        //[PermissionFilter(nameof(FL_BasisInformationController) + "_" + nameof(FL_BasisInformationController.GetList), AuthorizationConst.LIST)]
        public async Task<IActionResult>GetList(PagingModel<FL_BasisInformationDto> pagingQueryModel)
        {
            ////工厂
          //  pagingQueryModel.Model.CreateFactory = UserIdentity.Factory;
           

            IPageModel<FL_BasisInformationDto>
                result = await _service.GetList(pagingQueryModel);

            //result.PageData.ForEach(dto =>
            //{
            //    dto.Mark02 = _coreDBContext.FL_BasisInformationCheck.Where(x => x.BasisInformationID == dto.Id).Where(a=>a.auditFactory==dto.FL_BasisInformationCheck.auditFactory).FirstOrDefault()?.AuditStatus;
            //    if(dto.Mark02==null)
            //    {
            //        dto.Mark02 = "未审核";
            //    }
            //});
            return this.JsonSuccess(result);
        }

        /// <summary>
        /// 法律法规信息补录---查询
        ///</summary>
        /// <param name="pagingQueryModel"></param>
        /// <returns></returns>

        [HttpPost("GetListBL")]
        //[PermissionFilter(nameof(FL_BasisInformationController) + "_" + nameof(FL_BasisInformationController.GetList), AuthorizationConst.LIST)]
        public async Task<IActionResult> GetListBL(PagingModel<FL_BasisInformationDto> pagingQueryModel)
        {
            ////工厂
            //  pagingQueryModel.Model.CreateFactory = UserIdentity.Factory;
            if (pagingQueryModel.Model.FL_BasisInformationCheck != null)
            {
                pagingQueryModel.Model.FL_BasisInformationCheck.AuditStatus = "已审核";
            }

            IPageModel<FL_BasisInformationDto>
                result = await _service.GetList(pagingQueryModel);

           
            return this.JsonSuccess(result);
        }

        /// <summary>
        /// 导出
        ///</summary>
        /// <param name="pagingQueryModel"></param>
        /// <returns></returns>

        [HttpPost("Export")]
        [PermissionFilter(nameof(FL_BasisInformationController) + "_" + nameof(FL_BasisInformationController.Export), AuthorizationConst.EXPORT)]
        public async Task<IActionResult>
            Export(PagingModel<FL_BasisInformationDto>
                pagingQueryModel)
        {
            var fileName = await _service.Export(pagingQueryModel);
            if (string.IsNullOrWhiteSpace(fileName))
                return this.JsonFaild(NULL_DATA_FOR_EXCEL_EXPORT);
            return this.JsonSuccess(fileName);
        }


        /// <summary>
        /// 导入
        /// </summary>
        /// <param name="data"></param>
        /// <param name="file"></param>
        /// <returns></returns>
        [HttpPost("Import")]
        //[PermissionFilter(nameof(FX_EquipmentFacilitiesController) + "_" + "导入")]
        public async Task<IActionResult> ImportAsync([FromForm]String data, [FromForm]List<IFormFile> file)
        {
            var retMeg = await _service.ImportAsync(file[0], data);
            if (!retMeg.Any())
            {
                _message.SendMessage(new Toolkit.Message.Model.MessageModel()
                {
                    FromUser = UserIdentity.Id,
                    ToUser = _wrkerRelationsService.GetRoleUser(_businessOptions.AdminHSEDeptName).FirstOrDefault(),
                    //  Content = $"消息模块测试当前222时间:{DateTime.Now}",
                    Content = $"法律法规模块在[" + DateTime.Now + "]完成一次导入,请部门经理验收",
                    SendTime = DateTime.Now,
                    Ttitle = "操作程序-添加申请"
                });
                return this.JsonSuccess();
            }
            else
            {
                return this.JsonFaild(retMeg[0].ToString());
            }
        }

        /// <summary>
        /// 审批 
        ///</summary>
        /// <param name="dto">含审批表id，审批结果，审批意见</param>
        /// <returns></returns>
        [HttpPost("SaveSP")]
        //[PermissionFilter(nameof(FX_ProcessMediumRecordController) + "_" + nameof(FX_ProcessMediumRecordController.SaveAsync))]
        public async Task<IActionResult> SaveAsyncSP(FL_BasisInformationDto dto)
        {
            if(dto.Mark02== "已审核")
            {
                return this.JsonFaild("当前记录已经审核 无法再次审核！");
            }
            //   var entity = await _service.GetAsync(dto.Id);
            //   dto.Id=_coreDBContext.FL_BasisInformationCheck.Where(x=>x.auditFactory==dto)
            var CheckDto = new  FL_BasisInformationCheckDto();

            CheckDto.Id = dto.FL_BasisInformationCheck.Id;
            CheckDto.auditor = UserIdentity.Id;
            CheckDto.AuditStatus = "已审核";
            CheckDto.BasisInformationID = dto.Id;
            CheckDto.auditFactory = UserIdentity.Factory;
            CheckDto.IsDeleted = false;
            CheckDto.UpdateTime = System.DateTime.Now;
            CheckDto.UpdateUser = UserIdentity.Id;
            CheckDto.Mark01 = null;
            CheckDto.Mark02 = null;


           await _serviceCheck.UpdateAsync(CheckDto);
            return this.JsonSuccess(string.Empty);
        }
        #endregion

        /// <summary>
        /// 根据ID获取信息
        ///</summary>
        /// <param name="id"></param>
        /// <returns></returns>

        [HttpGet("Get")]
        public async Task<IActionResult> Get(Guid id)
        {
            var entity = await _service.GetAsync(id);
            if (entity == null) return this.JsonFaild("未找到对应数据:" + id);

            ////法律法规_标准库相关部门
            //var standardInformationDeptDto = Mapper.Map<List<FL_StandardInformationDeptDto>>(entity.FL_StandardInformations);
            //var standardInformationDept = standardInformationDeptDto?.Select(a =>
            //new
            //{
            //    departmentName = a.Mark01,//部门名称
            //    departmentID = a.Class,
            //    a.DeptType,
            //    a.DeptTypeText,//
            //    a.FitSituation,
            //    a.FitSituationOrNotDescribe,
            //    remarks = a.Remarks
            //});

            //  附件
            var attachmentList = await _coreDBContext.SysFile.Where(a => a.B_ID == id).Select(a => "/api/File/DownLoad?id=" + a.Id).ToListAsync();


            var retModel = new
            {
                FileLeveName = entity.FL_FileLevel.FileLeve,
                entity.Id,//id
                fileLeve = entity.FileLeve,
                entity.LawRegulationsName,//法律法规名称
                entity.Symbol,//文号/标准号
                entity.IssueDate,//颁布日期
                entity.ImplementationDate,//实施日期
                attachmentList, //附件
                entity.IssueSubject,//发布主体
                //                    //entity.UpdateTime,//更改时间
                //entity.ApplyClause,//适用条款
                //entity.DescribeForWork,//对应工作情况描述
                //entity.Remarks,
                //// DeptName = standardInformationDept.de
                ////  departmentId = entity.SysDepartment2.Id,
                //entity.FL_StandardInformations,
                //entity.Attachment,
                //entity.AttachmentName,
                //entity.UpLoadDate,
                //FL_StandardInformationDept1 = standardInformationDept?.Where(a => a.DeptType == "1").ToList(),//实施部门
                //FL_StandardInformationDept2 = standardInformationDept?.Where(a => a.DeptType == "2").ToList(),//实施部门
                //FL_StandardInformationDept3 = standardInformationDept?.Where(a => a.DeptType == "3").ToList(),//了解部门
                ////zxbmList = standardInformationDept?.Where(a => a.DeptType == "1" || a.DeptType == "2").Select(a => a.departmentName),//熟练掌握  //指导他人
                //standardInformationDept,


            };

            return this.JsonSuccess(retModel);
        }

        /// <summary>
        ///  修改
        ///</summary>
        /// <param name="dto">含审批表id，审批结果，审批意见</param>
        /// <returns></returns>
        [HttpPost("Save")]
        //[PermissionFilter(nameof(FX_ProcessMediumRecordController) + "_" + nameof(FX_ProcessMediumRecordController.SaveAsync))]
        public async Task<IActionResult> SaveAsync(FL_StandardInformationDto dto)
        {

            string SQLstr = @"UpDate  FL_BasisInformationCheck set  IsSupplement='是' " +
                " where BasisInformationID='" + dto.Id + "' and auditFactory='"+ UserIdentity .Factory+ "'";

            SqlParameter[] param1 = new SqlParameter[] { };
            List<SqlParameter> sqlParameterList1 = new List<SqlParameter>();
            param1 = sqlParameterList1.ToArray();
            try
            {
                var dataTable = _sQLHelper.ExecuteNonQuery(SQLstr, param1);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            //判断清单是否有记录
            if(_dbContext.FL_StandardInformation.Where(x => x.LawRegulationsName == dto.LawRegulationsName).Where(y => y.CreateFactory == UserIdentity.Factory).ToList().Count >0)
            {
                var entity = await _service.GetAsync(dto.Id);
                dto.Source = "基础库";
                dto.BasisInformationId = dto.Id;
                dto.UpdateUser = UserIdentity.Id;
                dto.FileLeve = entity.FileLeve;
                dto.IssueSubject = entity.IssueSubject;
                dto.Remarks = entity.Remarks;
                dto.State = "0";
                dto.Mark01 = entity.Mark01;
                dto.InputPerson = UserIdentity.Id;
                dto.InputTime = System.DateTime.Now;
                dto.CreateFactory = UserIdentity.Factory;//工厂
                dto.Id = _dbContext.FL_StandardInformation.Where(x => x.LawRegulationsName == dto.LawRegulationsName).Where(y => y.CreateFactory == UserIdentity.Factory).FirstOrDefault().Id;
               
                await _Informationservice.UpdateAsync(dto);
            }
            else
            {
                var entity = await _service.GetAsync(dto.Id);
                dto.Source = "基础库";
                dto.BasisInformationId = dto.Id;
                dto.UpdateUser = UserIdentity.Id;
                dto.FileLeve = entity.FileLeve;
                dto.IssueSubject = entity.IssueSubject;
                dto.Remarks = entity.Remarks;
                dto.State = "0";
                dto.Mark01 = entity.Mark01;
                dto.InputPerson = UserIdentity.Id;
                dto.InputTime = System.DateTime.Now;
                dto.CreateFactory = UserIdentity.Factory;//工厂
                dto.Id = Guid.NewGuid();
                await _Informationservice.InsertAsync(dto);
            }


            var oldEntity = await _dbContext.FL_StandardInformationDept.Where(x => x.LawRegulationsName == dto.Id && x.DeptType == "2").ToListAsync();
            oldEntity.ForEach(e => _dbContext.FL_StandardInformationDept.Remove(e));

            var newEntity = Mapper.Map<List<FL_StandardInformationDept>>(dto.FL_StandardInformationDept2);
            newEntity.ForEach(e => {
                e.LawRegulationsName = dto.Id; e.DeptType = "2"; e.DeptTypeText = "实施部门"; e.FitSituation = dto.FL_StandardInformationDept2.FirstOrDefault().FitSituation;
                e.FitSituationOrNotDescribe = dto.FL_StandardInformationDept2.FirstOrDefault().FitSituationOrNotDescribe;
            });
            // 
            await _dbContext.AddRangeAsync(newEntity);
            await _dbContext.SaveChangesAsync();

            var oldEntity3 = await _dbContext.FL_StandardInformationDept.Where(x => x.LawRegulationsName == dto.Id && x.DeptType == "3").ToListAsync();
            oldEntity3.ForEach(e => _dbContext.FL_StandardInformationDept.Remove(e));

            var newEntity3 = Mapper.Map<List<FL_StandardInformationDept>>(dto.FL_StandardInformationDept3);
            newEntity3.ForEach(e => { e.LawRegulationsName = dto.Id; e.DeptType = "3"; e.DeptTypeText = "了解部门"; });
            //
            await _dbContext.AddRangeAsync(newEntity3);
            await _dbContext.SaveChangesAsync();


            //dto.FL_StandardInformationDept1.FirstOrDefault().Class = await _dbContext.SysDepartment.Where(x => x.Name == "123").FirstOrDefault().Id;

            var oldEntity1 = await _dbContext.FL_StandardInformationDept.Where(x => x.LawRegulationsName == dto.Id && x.DeptType == "1").ToListAsync();
            oldEntity1.ForEach(e => _dbContext.FL_StandardInformationDept.Remove(e));

            var newEntity1 = Mapper.Map<List<FL_StandardInformationDept>>(dto.FL_StandardInformationDept1);
            newEntity1.ForEach(e => { e.LawRegulationsName = dto.Id; e.DeptType = "1"; e.DeptTypeText = "归口部门"; });
            //

            await _dbContext.AddRangeAsync(newEntity1);
            await _dbContext.SaveChangesAsync();


            try
            {
                _message.SendMessage(new Toolkit.Message.Model.MessageModel()
                {
                    FromUser = UserIdentity.Id,
                    ToUser = _wrkerRelationsService.GetRoleUser(_businessOptions.GKDeptName).FirstOrDefault(),
                    Content = $"法律法规信息补录模块在[" + DateTime.Now + "]完成一次信息补录,请部门经理验收",
                    SendTime = DateTime.Now,
                    Ttitle = "操作程序-添加申请"
                });

                _message.SendMessage(new Toolkit.Message.Model.MessageModel()
                {
                    FromUser = UserIdentity.Id,
                    ToUser = _wrkerRelationsService.GetRoleUser(_businessOptions.ZXDeptName).FirstOrDefault(),
                    Content = $"法律法规信息补录模块在[" + DateTime.Now + "]完成一次信息补录,请部门经理验收",
                    SendTime = DateTime.Now,
                    Ttitle = "操作程序-添加申请"
                });

                _message.SendMessage(new Toolkit.Message.Model.MessageModel()
                {
                    FromUser = UserIdentity.Id,
                    ToUser = _wrkerRelationsService.GetRoleUser(_businessOptions.LJDeptName).FirstOrDefault(),
                    Content = $"法律法规信息补录模块在[" + DateTime.Now + "]完成一次信息补录,请部门经理验收",
                    SendTime = DateTime.Now,
                    Ttitle = "操作程序-添加申请"
                });
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return this.JsonSuccess(string.Empty);
        }


        /// <summary>
        /// 附件上传----ZIP文件
        /// </summary>
        /// <param name="data"></param>
        /// <param name="file"></param>
        /// <returns></returns>
        [HttpPost("SaveFileName")]
        //[PermissionFilter(nameof(FX_EquipmentFacilitiesController) + "_" + "导入")]
        public async Task<IActionResult> SaveFileName(FL_BasisInformationDto dto)
        {
            var retMeg = "";
           // var retMeg = await _service.ImportAsync(file[0], data);
            if (!retMeg.Any())
            {
                _message.SendMessage(new Toolkit.Message.Model.MessageModel()
                {
                    FromUser = UserIdentity.Id,
                    ToUser = _wrkerRelationsService.GetRoleUser(_businessOptions.AdminHSEDeptName).FirstOrDefault(),
                    //  Content = $"消息模块测试当前222时间:{DateTime.Now}",
                    Content = $"法律法规模块在[" + DateTime.Now + "]完成一次导入,请部门经理验收",
                    SendTime = DateTime.Now,
                    Ttitle = "操作程序-添加申请"
                });
                return this.JsonSuccess();
            }
            else
            {
                return this.JsonFaild(retMeg[0].ToString());
            }
        }

    }
}
